import { createSlice } from '@reduxjs/toolkit';
import moment from 'moment';

const chatRecordSlice = createSlice({
	name: 'agent',
	initialState: [],
	reducers: {
		setChatRecord(state, action): any {
			console.log(action, 'action');
			if (action.payload instanceof Array) {
				return setShowTime(action.payload);
			} else {
				return setShowTime([...state, action.payload]);
			}
		},

		clearChatRecord() {
			return [];
		}
	}
});

const setShowTime = (state: any) => {
	let copyList: any = [...state];
	if (copyList.length !== 0) {
		let firstTime = copyList[0].date;
		copyList.forEach((item: any) => {
			if (moment(item.date).diff(moment(firstTime)) >= 300000) {
				firstTime = item.date;
				item.showTime = true;
			}
		});
	}
	return copyList;
};

export const { setChatRecord, clearChatRecord } = chatRecordSlice.actions;
export default chatRecordSlice.reducer;
